import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  Card,
  Table,
  Button,
  Input,
  Select,
  Tag,
  Space,
  Modal,
  message,
  Spin,
  Empty,
} from 'antd';
import { SearchOutlined, PlusOutlined, EditOutlined, DeleteOutlined, FilterOutlined, DownloadOutlined, ReloadOutlined } from '@ant-design/icons';
import { getApiList, deleteApi, batchDeleteApi } from '../../services/api';

const { Option } = Select;
const { Search } = Input;

const ApiManagement = () => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [apiList, setApiList] = useState([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [searchText, setSearchText] = useState('');
  const [statusFilter, setStatusFilter] = useState('');
  const [methodFilter, setMethodFilter] = useState('');
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [deleteModalVisible, setDeleteModalVisible] = useState(false);

  // Fetch API list
  const fetchApiList = async (params = {}) => {
    setLoading(true);
    try {
      const filterParams = {
        ...params,
        keyword: searchText,
        status: statusFilter,
        method: methodFilter,
      };
      const res = await getApiList(filterParams);
      if (res.success) {
        setApiList(res.data.items);
        setPagination({
          ...pagination,
          total: res.data.total,
          current: params.current || 1,
        });
      }
    } catch (error) {
      console.error('Failed to fetch API list:', error);
      message.error('获取API列表失败');
    } finally {
      setLoading(false);
    }
  };

  // Initial data fetch
  useEffect(() => {
    fetchApiList();
  }, []);

  // Handle search
  const handleSearch = () => {
    setPagination({ ...pagination, current: 1 });
    fetchApiList({ current: 1 });
  };

  // Handle page change
  const handlePageChange = (page, pageSize) => {
    setPagination({ ...pagination, current: page, pageSize });
    fetchApiList({ current: page, pageSize });
  };

  // Handle status filter change
  const handleStatusFilterChange = (value) => {
    setStatusFilter(value);
    setPagination({ ...pagination, current: 1 });
    fetchApiList({ current: 1 });
  };

  // Handle method filter change
  const handleMethodFilterChange = (value) => {
    setMethodFilter(value);
    setPagination({ ...pagination, current: 1 });
    fetchApiList({ current: 1 });
  };

  // Handle row selection change
  const onSelectChange = (newSelectedRowKeys) => {
    setSelectedRowKeys(newSelectedRowKeys);
  };

  // Handle create API
  const handleCreate = () => {
    navigate('/api/create');
  };

  // Handle edit API
  const handleEdit = (id) => {
    navigate(`/api/${id}`);
  };

  // Handle delete API
  const handleDelete = (id) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个API吗？删除后将无法恢复。',
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          const res = await deleteApi(id);
          if (res.success) {
            message.success('API删除成功');
            fetchApiList({ current: pagination.current });
          }
        } catch (error) {
          console.error('Failed to delete API:', error);
          message.error('API删除失败');
        }
      },
    });
  };

  // Handle batch delete
  const handleBatchDelete = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请选择要删除的API');
      return;
    }

    Modal.confirm({
      title: '批量删除',
      content: `确定要删除选中的 ${selectedRowKeys.length} 个API吗？删除后将无法恢复。`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          const res = await batchDeleteApi(selectedRowKeys);
          if (res.success) {
            message.success(`成功删除 ${res.data.deletedCount} 个API`);
            setSelectedRowKeys([]);
            fetchApiList({ current: pagination.current });
          }
        } catch (error) {
          console.error('Failed to batch delete APIs:', error);
          message.error('批量删除失败');
        }
      },
    });
  };

  // Handle export
  const handleExport = () => {
    message.info('导出功能正在开发中...');
  };

  // Handle refresh
  const handleRefresh = () => {
    fetchApiList({ current: pagination.current });
  };

  // Table columns
  const columns = [
    {
      title: 'API名称',
      dataIndex: 'name',
      key: 'name',
      ellipsis: true,
    },
    {
      title: 'URL',
      dataIndex: 'url',
      key: 'url',
      ellipsis: true,
    },
    {
      title: '方法',
      dataIndex: 'method',
      key: 'method',
      render: (method) => (
        <Tag color={
          method === 'GET' ? 'blue' :
          method === 'POST' ? 'green' :
          method === 'PUT' ? 'orange' :
          method === 'DELETE' ? 'red' : 'default'
        }>
          {method}
        </Tag>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => (
        <Tag color={status === 'active' ? 'green' : 'gray'}>
          {status === 'active' ? '启用' : '禁用'}
        </Tag>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      sorter: (a, b) => new Date(a.createdAt) - new Date(b.createdAt),
    },
    {
      title: '更新时间',
      dataIndex: 'updatedAt',
      key: 'updatedAt',
      sorter: (a, b) => new Date(a.updatedAt) - new Date(b.updatedAt),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button type="text" icon={<EditOutlined />} onClick={() => handleEdit(record.id)}>
            编辑
          </Button>
          <Button type="text" danger icon={<DeleteOutlined />} onClick={() => handleDelete(record.id)}>
            删除
          </Button>
        </Space>
      ),
    },
  ];

  // Row selection configuration
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  return (
    <div className="api-management">
      <Card className="mb-4">
        <Row gutter={[16, 16]}>
          <Col xs={24} sm={24} md={8} lg={8} xl={6}>
            <Search
              placeholder="搜索API名称或URL"
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
              onSearch={handleSearch}
              enterButton={<SearchOutlined />}
              allowClear
            />
          </Col>
          <Col xs={24} sm={24} md={8} lg={8} xl={6}>
            <Select
              placeholder="选择状态"
              value={statusFilter}
              onChange={handleStatusFilterChange}
              allowClear
              style={{ width: '100%' }}
            >
              <Option value="active">启用</Option>
              <Option value="inactive">禁用</Option>
            </Select>
          </Col>
          <Col xs={24} sm={24} md={8} lg={8} xl={6}>
            <Select
              placeholder="选择请求方法"
              value={methodFilter}
              onChange={handleMethodFilterChange}
              allowClear
              style={{ width: '100%' }}
            >
              <Option value="GET">GET</Option>
              <Option value="POST">POST</Option>
              <Option value="PUT">PUT</Option>
              <Option value="DELETE">DELETE</Option>
              <Option value="PATCH">PATCH</Option>
              <Option value="HEAD">HEAD</Option>
              <Option value="OPTIONS">OPTIONS</Option>
            </Select>
          </Col>
          <Col xs={24} sm={24} md={24} lg={24} xl={6}>
            <Space style={{ width: '100%' }}>
              <Button type="primary" icon={<PlusOutlined />} onClick={handleCreate}>
                新增API
              </Button>
              <Button danger icon={<DeleteOutlined />} onClick={handleBatchDelete} disabled={selectedRowKeys.length === 0}>
                批量删除
              </Button>
              <Button icon={<DownloadOutlined />} onClick={handleExport}>
                导出
              </Button>
              <Button icon={<ReloadOutlined />} onClick={handleRefresh} loading={loading}>
                刷新
              </Button>
            </Space>
          </Col>
        </Row>
      </Card>

      <Card>
        <Table
          rowSelection={rowSelection}
          columns={columns}
          dataSource={apiList}
          rowKey="id"
          loading={loading}
          pagination={pagination}
          onChange={handlePageChange}
          locale={{
            emptyText: loading ? <Spin /> : <Empty description="暂无API数据" />,
          }}
        />
      </Card>
    </div>
  );
};

export default ApiManagement;